'use strict'
const Controller = require('egg').Controller

class MainController extends Controller{
    async index(){
        this.ctx.body='你好'
    }

    async checkLogin(){
        let username = this.ctx.request.body.username
        let password = this.ctx.request.body.password
        const sql = " SELECT userName FROM admin_user WHERE userName = '"+username +
        "' AND password = '"+password+"'"
        const res = await this.app.mysql.query(sql)
        if(res.length>0){
            let openId = new Date().getTime()
            this.ctx.session.openId={'openId':openId}
            this.ctx.body={data:'登录成功',openId:openId}
        }else{
            this.ctx.body={data:'登录失败'}
        }
    }

    async checkSession(){
        this.ctx.body={data:'已登录'}
    }

    async addArticle(){
        let article = this.ctx.request.body

        const result = await this.app.mysql.insert('article',article)
        
        const insertId = result.insertId
        const affectedRows = result.affectedRows

        this.ctx.body={insertId:insertId,affectedRows:affectedRows}

    }

    async updateArticle(){
        let article = this.ctx.request.body
        const result = await this.app.mysql.update('article',article)
        const affectedRows= result.affectedRows
        this.ctx.body={affectedRows:affectedRows}
    }

    async getArticleList(){
        let sql = 'SELECT article.id as id,'+
        'article.title as title,'+
        'article.addTime as addTime '+
        'FROM article LEFT JOIN type ON article.type_id = type.id '+
        'ORDER BY article.id DESC '
        const result =await this.app.mysql.query(sql)
        this.ctx.body={
            data:result
        }
    }

    async removeArticle(){
        const id = this.ctx.params.id
        const res = await this.app.mysql.delete('article',{'id':id})
        this.ctx.body = {data:res}
    }

    async getArticleDetailById(){
        const id = this.ctx.params.id
        const sql='SELECT article.id as id,'+
        'article.title as title,'+
        'article.introduce as introduce,'+
        'article.article_content as article_content,'+
        "article.addTime as addTime "+
        'FROM article LEFT JOIN type ON article.type_id = type.Id '+
        'WHERE article.id='+id
        const res = await this.app.mysql.query(sql)
        this.ctx.body={
            data:res
        }
    }
}

module.exports= MainController